package com.oversea.interceptor;

import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class QueryConditionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 7027385721747664354L;
	
	private static final String QUERY_CONDITION_PARAM ="query_condition_save";
	
	private static final String QUERY_BACK_PARAM = "query_back";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		if (getQueryConditionValue()) {
			ActionContext.getContext().getSession().put(getActionPath(invocation), ActionContext.getContext().getParameters());
		}
		if (getQueryBackValue()) {
			ActionContext ac = invocation.getInvocationContext();
			
			Map<String, Object> map = (Map<String, Object>) ac.getSession().get(getActionPath(invocation));
			Map<String, Object> params = ac.getParameters();
			if (map != null) {
				map.putAll(params);
				ac.setParameters(map);
			}
		}
		return invocation.invoke();
	}

	private boolean getQueryConditionValue() {
		Object value = ActionContext.getContext().getParameters().get(QUERY_CONDITION_PARAM);
		if (value == null) {
			return false;
		}
		return Boolean.valueOf(valueOf(value));
	}
	
	private boolean getQueryBackValue() {
		Object value = ActionContext.getContext().getParameters().get(QUERY_BACK_PARAM);
		if (value == null) {
			return false;
		}
		return Boolean.valueOf(valueOf(value));
	}
	
	private String getActionPath(ActionInvocation invocation) {
		return ServletActionContext.getRequest().getRequestURI();
		//String actionName = invocation.getInvocationContext().getName();
		//return contextPath + actionName;
	}
	
	private String valueOf(Object obj) {
		String value = null;
		if (obj instanceof String[]) {
			value = ((String[]) obj)[0];
		} else {
			value = String.valueOf(obj);
		}

		return value;
	}
}
